<?php
/*
 module:		红娘管理
 create_time:	2022-03-04 16:27:06
 author:		
 contact:		
*/

namespace app\backend\controller;

use app\backend\model\SysSite as SysSiteModel;
use app\backend\model\ZhMatchmakerLevel;
use app\backend\service\ExportService;
use app\backend\service\ZhMatchmakerLevelService;
use app\backend\service\ZhMatchmakerService;
use app\backend\model\ZhMatchmaker as ZhMatchmakerModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\App;
use think\facade\Db;
use app\backend\model\Member as MemberModel;
use think\facade\Filesystem;

class ZhMatchmaker extends Admin
{


    /*首页数据列表*/
    function index()
    {
        if (!$this->request->isAjax()) {
            $res = ZhMatchmakerLevelService::indexList(formatWhere([
                'status' => 1
            ]), 100, 1);
            $this->view->assign('level_rows', $res['rows']);
            return view('index');
        } else {
            $limit  = $this->request->post('limit', 20, 'intval');
            $offset = $this->request->post('offset', 0, 'intval');
            $page   = floor($offset / $limit) + 1;

            $where                        = [];
            if( $this->request->param('nickname')!=""){
                $where['z.name'] = ['like',$this->request->param('nickname', '', 'serach_in')];
            }


             if( $this->request->param('real_name')!=""){
                 $where['m.real_name'] = ['like',$this->request->param('real_name', '', 'serach_in')];
             }
            if( $this->request->param('phone')!=""){
                $where['z.phone']              = $this->request->param('phone', '', 'serach_in');
            }
            if( $this->request->param('city')!=""){
                $where['z.city']              = $this->request->param('city', '', 'serach_in');
            }
            if( $this->request->param('is_personal')!=""){
                $where['z.is_personal']       = $this->request->param('is_personal', '', 'serach_in');
            }
             if( $this->request->param('level_id')!=""){
                 $where['z.level_id']       = $this->request->param('is_personal', '', 'serach_in');
             }
            $where['z.wxapp_id']          = session('backend.wxapp_id');
            $createtime_start             = $this->request->param('createtime_start', '', 'serach_in');
            $createtime_end               = $this->request->param('createtime_end', '', 'serach_in');
            $level_id                     = $this->request->param('level_id', '', 'serach_in');

            $expiretime_start = $this->request->param('expiretime_start', '', 'serach_in');
            $expiretime_end   = $this->request->param('expiretime_end', '', 'serach_in');

            $where['z.createtime'] = ['between', [strtotime($createtime_start), strtotime($createtime_end)]];
            // $where['expiretime'] = ['between',[strtotime($expiretime_start),strtotime($expiretime_end)]];


            $where['z.status']   = $this->request->param('status', '', 'serach_in');
            $where['z.level_id'] = $level_id;

            $order = $this->request->post('order', '', 'serach_in');    //排序字段 bootstrap-table 传入
            $sort  = $this->request->post('sort', '', 'serach_in');        //排序方式 desc 或 asc

            $field   = 'z.*,m.nickname, m.real_name,m.avatar';
            $orderby = ($sort && $order) ? $sort . ' ' . $order : 'z.matchmaker_id desc';


            $res = ZhMatchmakerService::indexList(formatWhere($where), $field, $orderby, $limit, $page);
            return json($res);
        }
    }

    function selectMember()
    {
        return view('select_member');
    }

    function selectList()
    {
        return view('select_list');
    }

    /*修改*/
    function update()
    {

        if (!$this->request->isPost()) {
            $matchmaker_id = $this->request->get('matchmaker_id', '', 'serach_in');
            if (!$matchmaker_id) $this->error('参数错误');
            $info                         = ZhMatchmakerModel::find($matchmaker_id)->toArray();

            $user=\app\backend\model\Member::find($info["u_id"]);
            if($user){
                $user=$user->toArray();
            }
            $info["nickname"]=$user["nickname"];
            $top_matchmaker_name          = ZhMatchmakerModel::where("matchmaker_id", $info["top_matchmaker_id"])->column("name");
            $info['top_matchmaker_name']  = $top_matchmaker_name[0];
            $level_name                   = ZhMatchmakerLevel::where("id", $info["level_id"])->column("name");
            $info['level_name']           = $level_name[0];
            $info['pictures']             = htmlspecialchars_decode($info['pictures']);
            $info['videos']               = htmlspecialchars_decode($info['videos']);
            if(empty($info['videos']) || $info['videos']=='null'){
                $info['videos'] = '[]';
            }
            $info['share_videos']               = htmlspecialchars_decode($info['share_videos']);
            if(empty($info['share_videos']) || $info['share_videos']=='null'){
                $info['share_videos'] = '[]';
            }
            $info['hand_success_videos']               = htmlspecialchars_decode($info['hand_success_videos']);
            if(empty($info['hand_success_videos']) || $info['hand_success_videos']=='null'){
                $info['hand_success_videos'] = '[]';
            }
            $info['summarize_videos']               = htmlspecialchars_decode($info['summarize_videos']);
            if(empty($info['summarize_videos']) || $info['summarize_videos']=='null'){
                $info['summarize_videos'] = '[]';
            }
            $info['hand_success_picture'] = htmlspecialchars_decode($info['hand_success_picture']);
            if(empty($info['hand_success_picture']) || $info['hand_success_picture']=='null'){
                $info['hand_success_picture'] = '[]';
            }
            if($info['u_id'] > 0){
                $user=MemberModel::find($info['u_id']);
                if($info["name"]=="" && ! empty($user)){
                    $info["name"]=$user["nickname"];
                }
                $info['member_name'] = $user["nickname"] ." ".$user["phone"];
            }


            $res = ZhMatchmakerLevelService::indexList(formatWhere([
                'status' => 1

            ]), 100, 1);


            $this->view->assign('level_rows', $res['rows']);
            $this->view->assign('info', checkData($info));
            return view('update');
        } else {
            $postField = 'head_portrait,nature,sex,summarize_txt,summarize_videos,share_videos,hand_success_videos,show_home,matchmaker_id,name,phone,work_years,level_id,top_matchmaker_id,age,send_word,hand_success_desc,id_number,wechat_number,u_id,province,city,county,address,service_zone,remarks,hand_success_num,status,pictures,videos,hand_success_picture,lower_matchmaker_num,boy_desc,girl_desc';
            $data      = $this->request->only(explode(',', $postField), 'post', null);
            $info      = ZhMatchmakerModel::find($data['matchmaker_id'])->toArray();
            $m_data=$this->request->only(explode(',', "nickname"), 'post', null);
            if (empty($data['level_id'])) {
                $this->error('请选择红娘等级');
            }

            $levelData = ZhMatchmakerLevelService::byId($data['level_id']);
            if (empty($levelData['expiry'])) {
                $this->error('红娘等级过期时间错误');
            }

            if ($info['level_id'] != $data['level_id']) {
                if ($levelData['unit'] == 1) {
                    $data['expiretime'] = time() + 30 * 60 * 60 * 24 * $levelData['expiry'];
                } else {
                    $data['expiretime'] = time() + 60 * 60 * 24 * 365 * $levelData['expiry'];
                }
            }

            $res     = ZhMatchmakerService::update($data);
            $wxappId = session('backend.wxapp_id');
            //判断红娘是否已经审核通过，审核通过，则会员表中的is_matchmaker更新为是红娘
            $r       = ZhMatchmakerModel::where(['matchmaker_id' => $data['matchmaker_id'], 'status' => 1, 'wxapp_id' => $wxappId])->find();
            /*if ($r) {
                $m_udata=['is_matchmaker' => 1];

                if($m_data['nickname']!=""){
                    $m_udata["nickname"]=$m_data['nickname'];
                }
                MemberModel::where(['uid' => $r['u_id'], 'wxapp_id' => $wxappId])->update($m_udata);
            }*/

            return json(['status' => '00', 'msg' => '修改成功']);
        }
    }

    /**
     * @return \think\response\Json|\think\response\View
     * @author  lwx
     */
    function add()
    {
        if (!$this->request->isPost()) {
            $res = ZhMatchmakerLevelService::indexList(formatWhere([
                'status' => 1
            ]), 100, 1);
            $this->view->assign('level_rows', $res['rows']);
            return view('add');
        } else {
            $postField          = 'head_portrait,nature,sex,summarize_txt,summarize_videos,share_videos,hand_success_videos,show_home,name,phone,work_years,level_id,top_matchmaker_id,age,send_word,hand_success_desc,id_number,wechat_number,u_id,province,city,county,address,service_zone,remarks,hand_success_num,status,pictures,videos,hand_success_picture,lower_matchmaker_num,boy_desc,girl_desc';
            $data               = $this->request->only(explode(',', $postField), 'post', null);
            $data['createtime'] = time();
            $data['wxapp_id']   = session('backend.wxapp_id');

            if (empty($data['level_id'])) {
                $this->error('请选择红娘等级');
            }

            $levelData = ZhMatchmakerLevelService::byId($data['level_id']);
            if (empty($levelData['expiry'])) {
                $this->error('红娘等级过期时间错误');
            }

            if ($levelData['unit'] == 1) {
                $data['expiretime'] = time() + 30 * 60 * 60 * 24 * $levelData['expiry'];
            } else {
                $data['expiretime'] = time() + 60 * 60 * 24 * 365 * $levelData['expiry'];
            }
            $res = ZhMatchmakerModel::create($data);
            return json(['status' => '00', 'msg' => '添加成功']);
        }
    }

    /*删除*/
    function delete()
    {
        $idx = $this->request->post('matchmaker_id', '', 'serach_in');
        if (!$idx) $this->error('参数错误');
        try {
            ZhMatchmakerModel::destroy(['matchmaker_id' => explode(',', $idx)], true);
        } catch (\Exception $e) {
            abort(config('my.error_log_code'), $e->getMessage());
        }
        return json(['status' => '00', 'msg' => '操作成功']);
    }

    /*查看详情*/
    function view()
    {
        $res = ZhMatchmakerLevelService::indexList(formatWhere([
            'status' => 1
        ]), 100, 1);
        $this->view->assign('level_rows', $res['rows']);
        $matchmaker_id = $this->request->get('matchmaker_id', '', 'serach_in');
        if (!$matchmaker_id) $this->error('参数错误');
        $info                         = \app\backend\model\ZhMatchmaker::alias('z')->leftJoin('member m', 'm.uid =z.u_id')->field("z.*,m.uid,m.nickname")->where(["z.matchmaker_id"=>$matchmaker_id])->find()->toArray();
        //nickname/
        $top_matchmaker_name          = ZhMatchmakerModel::where("matchmaker_id", $info["top_matchmaker_id"])->column("name");
        $info['top_matchmaker_name']  = $top_matchmaker_name[0];
        $level_name                   = ZhMatchmakerLevel::where("id", $info["level_id"])->column("name");
        $info['level_name']           = $level_name[0];
        $info['pictures']             = json_decode(htmlspecialchars_decode($info['pictures']), true);
        $info['videos']               = json_decode(htmlspecialchars_decode($info['videos']), true);
        $info['hand_success_picture'] = json_decode(htmlspecialchars_decode($info['hand_success_picture']), true);

        $this->view->assign('info', checkData($info));
        return view('view');
    }

    /**
     * 红娘的下级用户列表
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author  lwx
     */
    function childList()
    {
        $matchmaker_id = $this->request->get('matchmaker_id', '', 'serac
        h_in');
        if (!$matchmaker_id) $this->error('参数错误');
        $this->view->assign('matchmaker_id', $matchmaker_id);
        if ($matchmaker_id > 0) {
            session('matchmaker_id', $matchmaker_id);
        }
        if (!$this->request->isAjax()) {
            return view('list');
        } else {
            $matchmaker_id          = intval(session('matchmaker_id'));
            $limit                  = $this->request->post('limit', 20, 'intval');
            $offset                 = $this->request->post('offset', 0, 'intval');
            $page                   = floor($offset / $limit) + 1;
            $order                  = $this->request->post('order', '', 'serach_in');    //排序字段 bootstrap-table 传入
            $sort                   = $this->request->post('sort', '', 'serach_in');        //排序方式 desc 或 asc
            $field                  = "*";
            $orderby                = ($sort && $order) ? $sort . ' ' . $order : 'uid desc';
            $where                  = [];
            $where['matchmaker_id'] = $matchmaker_id;
            $res                    = ZhMatchmakerService::childList(formatWhere($where), $field, $orderby, $limit, $page);
            return json($res);
        }
    }

    function import()
    {
        $file      = $this->request->file("file");
        $save_name = Filesystem::disk('public')->putFile('file/xls', $file);
        $data      = baseFromExcel('/' . App::getRootPath() . 'public/uploads/' . $save_name);

        $filedData = [
            '姓名'             => 'name',
            '电话'             => 'phone',
            '年龄'             => 'age',
            '身份证号'         => 'id_number',
            '微信号'           => 'wechat_number',
            '用户ID'           => 'u_id',
            '下级佳人数'       => 'lower_matchmaker_num',
            '从业经验'         => 'work_years',
            '服务区域'         => 'service_zone',
            '简介'             => 'remarks',
            '省'               => 'province',
            '市'               => 'city',
            '区'               => 'county',
            '地址'             => 'address',
            '上级推荐人ID'     => 'top_matchmaker_id',
            '红娘等级ID'       => 'level_id',
            '牵手成功数量'     => 'hand_success_num',
            '牵线成功案例详情' => 'hand_success_desc',
            '红娘寄语'         => 'send_word',
            '状态'             => 'status',
            '红娘性质（1个人2机构3其他）'=>'nature',
            '男生概况'=>'boy_desc',
            '女生概况'=>'girl_desc',
            '总结文字'=>'summarize_txt',
        ];

        $status = [
            '通过'   => 1,
            '待审核' => 0,
            '拒绝'   => 2
        ];

        $newData = [];
        foreach ($data as $row) {
            $newRow = [];
            foreach ($row as $key => $datum) {
                $newRow[$filedData[$key]] = $datum;
            }

            $newRow['status'] = $status[$newRow['status']];

            $newRow['createtime'] = time();
            $newRow['wxapp_id']   = session('backend.wxapp_id');
            if (empty($newRow['level_id'])) {
                $this->error('请输入红娘等级');
            }
            $levelData = ZhMatchmakerLevelService::byId($newRow['level_id']);
            if (empty($levelData['expiry'])) {
                $this->error('红娘等级过期时间错误');
            }
            if ($levelData['unit'] == 1) {
                $newRow['expiretime'] = time() + 30 * 60 * 60 * 24 * $levelData['expiry'];
            } else {
                $newRow['expiretime'] = time() + 60 * 60 * 24 * 365 * $levelData['expiry'];
            }
            $newData[] = $newRow;
        }
        $res = ZhMatchmakerModel::insertAll($newData);
        return json(['status' => '00', 'msg' => '操作成功']);
    }

    function validProfile(){
        $info = SysSiteModel::where(['wxapp_id'=> session('backend.wxapp_id')])->field('id, wxapp_id, valid_profile')->find()->toArray();
        $this->view->assign('info',$info);
        return view('valid_profile');
    }

    function updateValidProfile(){
        $postField = 'id,valid_profile';
        $data               = $this->request->only(explode(',', $postField), 'post', null);
        SysSiteModel::where(['id'=> $data['id']])->update(['valid_profile' => $data['valid_profile']]);
        return json(['status' => '00', 'msg' => '操作成功']);
    }

      // 导出
    public function export()
    {
        $expCellName = [
            'matchmaker_id' => 'Id',
            'name' => '姓名',
            'phone'             => '手机号',
            ];
        $export      = new ExportService();
        $spreadsheet = null;
        $sheet       = null;
        $limit   = 10000;
        $offset  = 0;
        $page    = floor($offset / $limit) + 1;
        $res = \app\backend\model\ZhMatchmaker::alias('a') ->field(["a.matchmaker_id"])->order("a.matchmaker_id desc ")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

        $total=$res["total"];

        if ($total == 0) {
            $this->error('导出数据为空');
        }
        $current_total = 0;     // 当前已循环条数
        $page_size     = 50000;
        $total_page    = intval(ceil($total / $page_size));

        for ($i = 0; $i < $total_page; $i++) {
            $page         = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;
              $res = \app\backend\model\ZhMatchmaker::alias('a') ->field(["a.matchmaker_id","a.name","a.phone"])->order("a.matchmaker_id desc ")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
            $list=$res["data"];
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('红娘数据-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page'          => $page,
                'page_size'     => 10000,      // 如果传了 current_total 则 page_size 就不用了
                'current_total' => $current_total,      // page_size 是 order 的，但是 newList 其实是 order_item 的
                'is_last_page'  => $is_last_page
            ]);
        }
    }
}

